//
//  XQEmergencyController.m
//  JoinPeso
//
//  Created by 小琦 on 2024/11/26.
//

#import "XQEmergencyController.h"
#import "XQEmergencyHeaderView.h"
#import "XQAlertController.h"
#import "XQEmergencyCell.h"
#import "XQCustomOptionalPop.h"
#import <Contacts/Contacts.h>
#import <Contacts/CNLabeledValue.h>
#import <ContactsUI/ContactsUI.h>

@interface XQEmergencyController ()<UITableViewDelegate,UITableViewDataSource,CNContactPickerDelegate>

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,copy) NSArray *dataSource;

@property (nonatomic,strong) NSMutableArray *dataArr;

@property (nonatomic,strong) XQButton *bottomButton;

@property (nonatomic,strong) NSIndexPath *phoneIndexPath;

@end

@implementation XQEmergencyController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self makeUI];
    [self makeConstraints];
    self.startInterval = [XQTimeTool nowTimeStamp];
    [self refreshData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self startLocation];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self stopLocation];
}

- (void)makeUI {
    self.view.backgroundColor = kCardColor;
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomButton];
}

- (void)makeConstraints {
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo([UIScreen mainScreen].topHeight);
        make.left.equalTo(@12);
        make.right.equalTo(@-12);
        make.bottom.offset(-[UIScreen mainScreen].bottomHeight - 100);
    }];
    [self.bottomButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-[UIScreen mainScreen].bottomHeight - 20);
        make.left.right.equalTo(@0);
    }];
}

- (void)refreshData {
    NSDictionary *dic = @{
        @"accommodate" : self.cardId
    };
    [XQHUD showLoadingInView:self.view];
    @weakify(self)
    [XQAFNetworking postWithUrl:[XQNetManager getAbsolutePath:@"/direct/covering"] pars:dic callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
        @strongify(self);
        [XQHUD hideLoadindInView:self.view];
        if ([responseObject[@"concept"] integerValue] == 0) {
            [self.dataArr removeAllObjects];
            NSDictionary *accomplish = responseObject[@"accomplish"];
            id letters = accomplish[@"letters"];
            if ([letters isKindOfClass:[NSArray class]]) {
                self.dataSource = letters;
                for (int i = 0; i < self.dataSource.count; i++) {
                    NSDictionary *currentDic = self.dataSource[i];
                    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                    if ([currentDic[@"chance"] description].length) {
                        [dic setValue:currentDic[@"chance"] forKey:@"chance"];
                    }
                    if ([currentDic[@"brighter"] description].length) {
                        [dic setValue:currentDic[@"brighter"] forKey:@"brighter"];
                    }
                    if ([currentDic[@"astrophysics"] description].length) {
                        [dic setValue:currentDic[@"astrophysics"] forKey:@"astrophysics"];
                    }
                    [self.dataArr addObject:dic];
                }
                [self.tableView reloadData];
            }
        }
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *dic = self.dataSource[indexPath.section];
    
    NSMutableDictionary *valueData = self.dataArr[indexPath.section];
    
    XQEmergencyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XQEmergencyCell" forIndexPath:indexPath];
    cell.contactView.topTitle = dic[@"appear"];
    cell.contactView.content = [self getContactContet:valueData[@"astrophysics"] emissions:dic[@"emissions"]];
    cell.contactView.placeholder = dic[@"table"];
    cell.phoneView.topTitle = dic[@"visorsats"];
    cell.phoneView.placeholder = dic[@"observational"];
    
    NSString *chance = [valueData[@"chance"] description].length == 0 ? @"" : valueData[@"chance"];
    NSString *brighter = [valueData[@"brighter"] description].length == 0 ? @"" : valueData[@"brighter"];
    if (chance.length && brighter.length) {
        cell.phoneView.content = [NSString stringWithFormat:@"%@ %@",chance,brighter];
    }else if (chance.length) {
        cell.phoneView.content = [NSString stringWithFormat:@"%@",chance];
    }else if (brighter.length) {
        cell.phoneView.content = [NSString stringWithFormat:@"%@",brighter];
    }else {
        cell.phoneView.content = @"";
    }
   
    
    @weakify(self);
    cell.contactView.buttonHandle = ^{
        @strongify(self)
        [self didSelectAtIndexPath:indexPath];
    };
    cell.phoneView.buttonHandle = ^{
        @strongify(self);
        self.phoneIndexPath = indexPath;
        [self openContact:indexPath];
    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 192;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    NSDictionary *dic = self.dataSource[section];
    
    XQEmergencyHeaderView *headerView = [[XQEmergencyHeaderView alloc] init];
    [headerView setTitle:dic[@"won"]];
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 36;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 20;
}

#pragma mark - CNContactPickerDelegate

- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
    NSString *fullName = [NSString stringWithFormat:@"%@ %@", contact.givenName, contact.familyName];
    
    // 获取手机号
    NSString *phoneNumber = nil;
    if (contact.phoneNumbers.count > 0) {
        CNPhoneNumber *phone = contact.phoneNumbers.firstObject.value;
        phoneNumber = phone.stringValue;
    }
    
    // 存值
    NSMutableDictionary *dic = self.dataArr[self.phoneIndexPath.section];
    [dic setValue:fullName forKey:@"chance"];
    [dic setValue:phoneNumber forKey:@"brighter"];
    
    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:self.phoneIndexPath.section];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    [self reportContact];
}

- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - setter

- (void)setTopTitle:(NSString *)topTitle {
    [self.navigationBar setTitle:topTitle];
}

#pragma mark - private

- (void)clickNextButton {
    
    NSDictionary *dic = @{
        @"accommodate" : self.cardId,
        @"accomplish" : [self.dataArr yy_modelToJSONString]
    };
    [XQHUD showLoadingInView:self.view];
    @weakify(self)
    [XQAFNetworking postWithUrl:[XQNetManager getAbsolutePath:@"/direct/monitoring"] pars:dic callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
        @strongify(self);
        [XQHUD hideLoadindInView:self.view];
        if ([responseObject[@"concept"] integerValue] == 0) {
            [self reportRisk];
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            [XQToast showMsg:responseObject[@"loon"]];
        }
    }];
}

- (void)didSelectAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *dic = self.dataSource[indexPath.section];
    
    NSString *title = dic[@"appear"];
    NSArray *array = dic[@"emissions"];
    
    NSMutableArray *totalArray = [NSMutableArray array];
    for (NSDictionary *dic in array) {
        NSString *text = dic[@"chance"];
        if (text.length) {
            [totalArray addObject:text];
        }
    }
    
    // 获取值
    NSMutableDictionary *valueData = self.dataArr[indexPath.section];
    NSString *value = valueData[@"astrophysics"];

    XQCustomOptionalPop *popView = [[XQCustomOptionalPop alloc] initWithTitle:title datas:totalArray];
    if (value.length) {
        NSString *chance = [self getContactContet:value emissions:array];
        [popView setSelctData:chance];
    }else {
        [popView setSelctData:totalArray.firstObject];
    }
    
    XQPopupAnimView *anim = [[XQPopupAnimView alloc] initWithAnimationType:XQPopupAnimationCenter customView:popView];
    anim.needCover = YES;
    anim.makeCustomConstraints = ^(XQPopupAnimView *animView, UIView *customView) {
        [customView mas_remakeConstraints:^(MASConstraintMaker *make) {
            (void)make.center;
        }];
    };
    
    
    [anim showInView:self.view completion:^{}];
    
    @weakify(anim)
    popView.confimHandle = ^(NSString * _Nonnull data) {
        @strongify(anim);
        
        // 存值
        NSMutableDictionary *saveDic = self.dataArr[indexPath.section];
        NSString *spacemobile = [self getSpacemobile:data emissions:dic[@"emissions"]];
        [saveDic setValue:spacemobile forKey:@"astrophysics"];
        
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:indexPath.section];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        
        [anim hideAndCompletion:^{}];
        
    };
}

- (void)openContact:(NSIndexPath *)indexPath {
    CNContactStore *contactStore = [[CNContactStore alloc] init];
    [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            [self openContacts];
        } else {
            // 权限被拒绝，提示用户
            dispatch_async(dispatch_get_main_queue(), ^{
                [XQAlertController showAccessDeniedAlert:self message:@"Please enable access to Contacts in Settings."];
            });
        }
    }];
}

- (NSString *)getSpacemobile:(NSString *)chance emissions:(NSArray *)emissions{
    NSString *spacemobile = @"";
    for (NSDictionary *dic in emissions) {
        NSString *ch = dic[@"chance"];
        if ([ch isEqualToString:chance]) {
            spacemobile = dic[@"spacemobile"];
            break;
        }
    }
    return spacemobile;
}

- (NSString *)getContactContet:(NSString *)value emissions:(NSArray *)emissions {
    NSString *chance = @"";
    for (NSDictionary *dic in emissions) {
        NSString *spacemobile = dic[@"spacemobile"];
        if ([value isEqualToString:spacemobile]) {
            chance = dic[@"chance"];
        }
    }
    return chance;
}

- (void)openContacts {
    dispatch_async(dispatch_get_main_queue(), ^{
        CNContactPickerViewController *picker = [[CNContactPickerViewController alloc] init];
        picker.delegate = self; // 确保遵循 CNContactPickerDelegate 协议
        [self presentViewController:picker animated:YES completion:nil];
    });
}

- (void)reportContact {
    NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey,CNContactBirthdayKey,CNContactEmailAddressesKey];
    CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
    CNContactStore *contactStore = [[CNContactStore alloc] init];

    __block NSMutableArray *dataSource = [NSMutableArray array];
        
    [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        
        NSString *givenName = contact.givenName;
        NSString *familyName = contact.familyName;
        NSString *nameStr = [NSString stringWithFormat:@"%@ %@",givenName,familyName];
        
        NSArray *phoneNumbers = contact.phoneNumbers;
        NSMutableArray *phoneArr = [NSMutableArray array];
        for (CNLabeledValue *labelValue in phoneNumbers) {
            CNPhoneNumber *phoneNumber = labelValue.value;
            [phoneArr addObject:phoneNumber.stringValue];
        }
        NSString *phoneString = [phoneArr componentsJoinedByString:@","];
        
        
        NSString *emailValue = @"";
        for (CNLabeledValue *email in contact.emailAddresses) {
            NSString *emailString = email.value;
            emailValue = emailString;
        }
        
        
        NSString *birthDay = @"";
        if (contact.birthday) {
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
            birthDay = [dateFormatter stringFromDate:contact.birthday.date];
        }
        
        NSMutableDictionary * myDict = [NSMutableDictionary dictionary];
        
        [myDict setValue:phoneString.length ? phoneString : @"" forKey:@"monitoring"];
        [myDict setValue:birthDay.length ? birthDay : @"" forKey:@"syndrome"];
        [myDict setValue:emailValue.length ? emailValue : @"" forKey:@"protection"];
        [myDict setValue:nameStr.length ? nameStr : @"" forKey:@"chance"];
        [myDict setValue:@"" forKey:@"quiet"];
    
        NSTimeInterval currentTimestamp = [[NSDate date] timeIntervalSince1970];
        long long timestampInMilliseconds = (long long)currentTimestamp;
        NSString *currentTimestampStr = [NSString stringWithFormat:@"%lld",timestampInMilliseconds];
        [myDict setValue:currentTimestampStr forKey:@"manage"];
        [myDict setValue:currentTimestampStr forKey:@"cancel"];
        
        [dataSource addObject:myDict];
        
    }];
    
    NSString *jsonString = [dataSource yy_modelToJSONString];
    
    [XQAFNetworking postWithUrl:[XQNetManager getAbsolutePath:@"/direct/investments"] pars:@{@"accomplish" : jsonString} callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
        
    }];
}

- (void)reportRisk {
    [XQGoogleMarket reportRiskWithType:@"7" longitude:self.longitude latitude:self.latitude startTime:self.startInterval endTime:[XQTimeTool nowTimeStamp] orderId:@""];
}

#pragma mark - lazy

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.layer.cornerRadius = 15;
        _tableView.backgroundColor = kCardColor;
        [_tableView setContentInset:UIEdgeInsetsMake(20, 0, 0, 0)];
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        [_tableView registerClass:[XQEmergencyCell class] forCellReuseIdentifier:@"XQEmergencyCell"];
    }
    return _tableView;
}

- (XQButton *)bottomButton {
    if (!_bottomButton) {
        _bottomButton = [[XQButton alloc] initWithTitle:@"Next"];
        @weakify(self);
        _bottomButton.onTapHandle = ^{
            @strongify(self);
            [self clickNextButton];
        };
    }
    return _bottomButton;
}

- (NSArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSArray array];
    }
    return _dataSource;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

@end
